package com.le.tester.book.concurrentchallenge.synchronizedUtil14;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * createTime：2025-05-22 14:07
 * description：使用Lock来实现信号量
 */
public class SemaphoreOnLock {
    private final Lock lock = new ReentrantLock();

    private final Condition permitaAvailable = lock.newCondition();

    private int permits;

    public SemaphoreOnLock(int initPermits) {
        lock.lock();
        try {
            permits = initPermits;
        } finally {
            lock.unlock();
        }
    }


    public void acquire() throws InterruptedException {
        lock.lock();
        try {
            while (permits <= 0) {
                permitaAvailable.await();
            }
            --permits;
        } finally {
            lock.unlock();
        }
    }

    public void release() throws InterruptedException {
        lock.lock();
        try {
            while (permits <= 0) {
                permitaAvailable.await();
            }
        } finally {
            lock.unlock();
        }
    }

}
